<HTML>
<HEAD>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<script src="/resource/jquery.js"></script>
<script src="/resource/jquery.cookie.js"></script>
<script src="/resource/json.js"></script>
<style>
input {
	height:30px;
}
#footer {
   position:absolute;
   bottom:0;
   left:0px;
   width:100%;
   height:30px;   /* Height of the footer */
   background:lightgray;
   padding:0px;
   padding-top:10px;
   padding-bottom: 10px;
}
#div_toolbar {
  float:left;
  padding-left: 10px;
}

#div_logout {
  float:right;
  padding-right: 10px;
}
#div_msg_list {
  float: left;
  padding-left: 10px;
  width: 45%;
  position:absolute;
  overflow:auto;
  height: 600px;
  overflow-y:scroll;
}
#div_msg_list div {
  float:left;
  width:100%;
  position:relative;
}
#div_user_list {
  float: right;
  padding-right: 10px;
  width: 30%;
  height:600px;
  overflow-y:scroll;
}
#div_user_total {
    float: left;
    padding-left: 50px;
    padding-top: 5px;
    width: 200px;
}
</style>
<script type="text/javascript">
var qs = (function(a) {
    if (a == "") return {};
    var b = {};
    for (var i = 0; i < a.length; ++i)
    {
        var p=a[i].split('=');
        if (p.length != 2) continue;
        b[p[0]] = decodeURIComponent(p[1].replace(/\+/g, " "));
    }
    return b;
})(window.location.search.substr(1).split('&'));

var name = qs["uname"] || $.cookie("uname");
var uId = qs["uid"] || $.cookie("uid");
var url = "http://10.0.0.40:9090";

if (name == null || uId == null) {
	alert("Never logined.");
	$(location).attr('href', '/login.html');
}

function uuid() {
	var result='';
	for(var i=0; i<32; i++)
		result += Math.floor(Math.random()*16).toString(16).toUpperCase();
	return result
}

function setCookie(user){
	$.cookie("uname", user.name, {path:"/"});
	$.cookie("uid", user.id, {path:"/"});
}

function removeCookie() {
	$.cookie("uname", null, {path:"/"});
	$.cookie("uid", null, {path:"/"});
}

function logoutSuccess(code) {
	if (code == 1) return true;

	return false;
}

function appendChatMsg(message) {
	$("#div_msg_list").append("<div>" + message + "</div>");

	scrollToBottom("#div_msg_list");
}

function appendUserMsg(message) {
	$("#div_user_list").append("<div>" + message + "</div>");

	scrollToBottom("#div_user_list");
	updateUsersCount();
}

function wrapChatMsg(message) {
	if (!message) return;

	//replace ' with "
	var re = new RegExp("(')", 'ig');
	message = message.replace(re, '"');
	
	other = $("#slt_user_list").val();
	other = (other == 'All') ? "所有人" : other;
	return encodeURI("<script>parent.appendChatMsg('【"+ name +"】对【"+ other +"】说："+ message +"')<\/script>");
}

function generateUUID(){
	uuid = uuid();
	$('#checkpoint').val(uuid);

	return uuid;
}

function getUUID() {
	return $('#checkpoint').val();
}

function setUUID(uuid) {
	$('#checkpoint').val(uuid);
}

function appendUser(name, uuid) {
	if (uuid != null && kickSelf(name, uuid)) {
		$(location).attr('href', '/login.html');
		return;
	}

	removeUser(name);
	
	$("#slt_user_list").append(
		$("<option></option>").attr("value", name).text(name)
	);
	appendUserMsg("【"+ name +"】进入房间");
	if (uuid != null) setUUID(uuid);

	updateUsersCount();
}

function kickSelf(new_login_name, new_uuid) {
	uuid = getUUID();
	if ((uuid != new_uuid) && (name == new_login_name)) {
		disconnect();
		alert("您已在其它地方登录，已退出");
		return true;
	}

	return false;
}

function connect(url, uId) {
	$("#pipeFrame").attr("src", url + uId);
}

function disconnect() {
	$("#pipeFrame").attr("src", '');
}

function wrapUserLogoutMsg(name) {
	if (!name) return;

	return encodeURI("<script>parent.removeUser('"+ name +"')<\/script>");
}

function removeUser(name) {
	result = $("#slt_user_list option[value="+name+"]").remove();

	if (result != null && result.length > 0) {
		appendUserMsg("【"+ name +"】退出房间");
		updateUsersCount();
	}
}

function sendMsg(from, to, message, success, error){
	$.ajax({ 
		type: 'GET',
		url: url + "/xroom/send.do",
		dataType: "jsonp",
		data: {
			from: from,
			to: to,
			message : message
		},
		success : success,
		error : error
	})
}

function displayMsg(msg) {
	$("#div_msg_show").html(msg);
}

function clear(div) {
	$(div).html("");
}

function resize(div) {
	h = $(window).height() - 65;
    $(div).css({'height':h});
}

function scrollToBottom(div) {
	$(div).scrollTop($(div)[0].scrollHeight);
}

function getUsersCount() {
	return $("#slt_user_list option").length - 1;
}

function updateUsersCount() {
	countStr = "共 " + getUsersCount() + " 用户同时在线";
	$("#div_user_total").html(countStr);
}

$(document).ready(function() {
	//loading all login user list
	$.ajax({ 
		type: 'GET',
		url: url + "/user/list.do",
		dataType: "jsonp",
		success : function(data){
			data = JSON.parse(data);
			//format user list selection
			userList = data.data;
			
			$.each(userList, function(index, user) {
				appendUser(user.name);
			})
		},
		error : function(xhr, ajaxOptions, thrownError){
		}
	})
	
	//init btns
	$("#btn_logout").click(function(){
		$.ajax({ 
			type: 'GET',
			url: url + "/user/logout.do",
			dataType: "jsonp",
			data: {
				name: name
			},
			success : function(data){
				data = JSON.parse(data);
				//redirect to login page
				if (logoutSuccess(data.message.code)) {
					
					displayMsg("Send logout message...");
					message = wrapUserLogoutMsg(name);
					sendMsg(name, 'All', message, function() {
						displayMsg("Success send message...");
						removeCookie();
						//redirect
						$(location).attr('href', '/login.html');
					});
					
				}
				else {
					displayMsg("Logout error : can not logout.");
				};
			},
			error : function(xhr, ajaxOptions, thrownError){
			}
		})
	})

	$("#btn_send_msg").click(function(){
		//wrap messages
		message = wrapChatMsg($("#txt_msg").val());
		if (!message) return;
		
		$("#btn_send_msg").attr("disabled","disabled");
		
		sendMsg(name, $("#slt_user_list").val() ,message, function(){
			//clear text input
			$("#txt_msg").val("");
		});
		
		$("#btn_send_msg").removeAttr("disabled");
	})
	
	$("#btn_clear_msg").click(function(){
		clear("#div_msg_list");
	});

	$("#div_user_name").append(name);

	//add keypress
	$("#txt_msg").keypress(function (e) {
        if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
            $("#btn_send_msg").click();
            return false;
        } else {
            return true;
        }
    });

    //resize
    $(window).resize(function(){
    	resize("#div_user_list");
    	scrollToBottom("#div_user_list");

    	resize("#div_msg_list");
    	scrollToBottom("#div_msg_list");
	})
	
	//Set receive message address
	connect("http://10.0.0.40:8000/test/", uId);

    resize("#div_user_list");
    resize("#div_msg_list");
})
</script>

</HEAD>
<BODY>
<div id="test"> </div>
<div id="room_main">
  <div id="div_user_list">
  </div>
  
  <div id="div_msg_list">
  </div>
</div>
<div id="footer">
  <div id="div_toolbar">
  	对<select id="slt_user_list"><option>All</option></select>说：<input type="text" id="txt_msg" value="" size="100"/><input type="button" id="btn_send_msg" value="Send" /> &nbsp; <input type="button" id="btn_clear_msg" value="Clear" />
  </div>
  <div id="div_user_total"></div>
  <div id="div_logout">
  	<div id="div_user_name" style="float:left;padding:5px;font:20 black">当前用户：</div>&nbsp;<div  style="float:left;"><input type="button" id="btn_logout" value="Logout" /></div>
  </div>
</div>
<div id="div_msg_show"></div>

<input type="hidden" id="checkpoint"  value=""/>
<iframe id="pipeFrame" name="pipeFrame" src="" style="display:none"></iframe>

</BODY>
</HTML>
